<template>
  <div class="app-container">
    <div v-show="baseEl">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="128px">
      <el-form-item :label="$t('station.name')" prop="name">
        <el-input
          v-model="queryParams.name"
          :placeholder="$t('station.name')"
          clearable
          @keyup.enter.native="handleQuery"
        /> 
      </el-form-item>
      <el-form-item :label="$t('station.state')" prop="state">
        <el-select v-model="queryParams.state" :placeholder="$t('station.state')" clearable>
          <el-option
            v-for="dict in dict.type.common_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{$t('common.search')}}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{$t('common.reset')}}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ems:station:add']"
        >{{$t('common.add')}}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ems:station:edit']"
        >{{$t('common.modify')}}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ems:station:remove']"
        >{{$t('common.delete')}}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ems:station:export']"
        >{{$t('common.export')}}</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="stationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column :label="$t('station.icon')" align="center" >
        <template slot-scope="scope">
          <img :src="baseUrl+scope.row.icon" style="width: 30px;height: 30px;" alt="">
        </template>
      </el-table-column>
      <el-table-column :label="$t('station.name')" align="center" prop="name" />
      <el-table-column :label="$t('station.company')" align="center" prop="companyName" />
      <el-table-column :label="$t('station.group')" align="center" prop="deptName" />
      <el-table-column :label="$t('station.admin')" align="center" prop="masterName" />
      <el-table-column :label="$t('station.electricityTotal')" align="center" prop="sumEnergy" >
        <template slot-scope="scope">
          {{scope.row.sumEnergy+' '+scope.row.unit}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('station.powerToatl')" align="center" prop="sumPower" >
        <template slot-scope="scope">
          {{scope.row.sumPower+' '+scope.row.powerUnit}}
        </template>
      </el-table-column>
      <el-table-column :label="$t('station.latitude')" align="center" prop="longitude" />
      <el-table-column :label="$t('station.longitude')" align="center" prop="latitude" />
      <el-table-column :label="$t('station.address')" align="center" prop="address" />
      <el-table-column :label="$t('station.state')" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.common_status" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column :label="$t('station.operator')" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-setting"
            @click="deviceManager(scope.row)"
            v-hasPermi="['ems:station:edit']"
          >{{$t('station.manage')}}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ems:station:edit']"
          >{{$t('common.modify')}}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ems:station:remove']"
          >{{$t('common.delete')}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    </div>
    <div v-show="appendEl">
      <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-close"
          size="mini"
          @click="handleCloseEl"
        >{{$t('common.close')}}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="openSelectDevice"
        >{{$t('common.add')}}</el-button>
      </el-col>
    </el-row>
      <el-table v-loading="loading" :data="deviceList">
        <el-table-column :label="$t('station.deviceName')" align="center" prop="name" />
        <el-table-column :label="$t('station.deviceCode')" align="center" prop="code" />
        <el-table-column :label="$t('station.latitude')" align="center" prop="latitude" />
        <el-table-column :label="$t('station.longitude')" align="center" prop="longitude" />
        <el-table-column :label="$t('station.address')" align="center" prop="address" />
        <el-table-column :label="$t('station.deviceState')" align="center" prop="inline" >
          <template slot-scope="scope">
            <dict-tag :options="dict.type.online_status" :value="scope.row.inline"/>
          </template>
        </el-table-column>
        <el-table-column :label="$t('station.updateTime')" align="center" prop="lastReceiveStatusTime" width="180"></el-table-column>
        <el-table-column :label="$t('common.operator')" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">   
            
            <el-button
              size="mini"
              type="text"
              icon="el-icon-finished"
              @click="handleDefaultDisplayDevice(scope.row)"
              v-if="addBindForm.defaultDeviceId!==scope.row.id"
            >{{$t('station.setDefaultDisplay')}}</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleRemBindingDevice(scope.row)"
              v-hasPermi="['device:device:remove']"
            >{{$t('common.delete')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加或修改设备站点对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="850px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item :label="$t('station.icon')" prop="icon" >
          <image-upload v-model="form.icon" :limit="1" :isShowTip="false" />
        </el-form-item>
        <el-form-item :label="$t('station.name')" prop="name">
          <el-input v-model="form.name" :placeholder="$t('station.name')" />
        </el-form-item>
        <el-form-item :label="$t('station.electricityTotal')" prop="sumEnergy">
          <el-input-number v-model="form.sumEnergy" :placeholder="$t('station.electricityTotal')" style="width:430px;"/> 
          <el-select v-model="form.unit" :placeholder="$t('station.unit')" style="margin-left:13px">
              <el-option value="kwh" label="kWh" />
              <el-option value="Wh" label="Wh" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('station.powerToatl')" prop="sumPower">
          <el-input-number v-model="form.sumPower" :placeholder="$t('station.powerToatl')" style="width:430px;"/> 
          <el-select v-model="form.powerUnit" :placeholder="$t('station.unit')" style="margin-left:13px">
              <el-option value="kW" label="kW" />
              <el-option value="W" label="W" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('station.company')" prop="companyId">
          <el-select v-model="form.companyId" :placeholder="$t('station.company')">
            <el-option
              v-for="company in companyList"
              :key="company.id"
              :label="company.name"
              :value="company.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('station.group')" prop="deptId">
          <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" :placeholder="$t('station.group')" style="width: 660px;"/>
        </el-form-item>
        <el-form-item :label="$t('station.admin')" prop="masterName">
          <el-input v-model="form.masterName" :placeholder="$t('station.admin')" >
            <el-button size="mini" type="text" @click="onOpen" style="padding:0 15px 0 15px;" slot="append">{{$t('station.chooseAdmin')}}</el-button>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('station.latitude')" prop="latitude">
          <el-input v-model="form.latitude" :placeholder="$t('station.latitude')" />
        </el-form-item>
        <el-form-item :label="$t('station.longitude')" prop="longitude">
          <el-input v-model="form.longitude" :placeholder="$t('station.longitude')" />
        </el-form-item>
        <el-form-item :label="$t('station.address')" prop="address">
          <el-input readonly v-model="form.address" :placeholder="$t('station.address')" style="width: 660px;">
            <el-button slot="append" @click="POISearchDialog">{{$t('station.selectAddress')}}</el-button>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('station.state')" prop="state">
          <el-select v-model="form.state" :placeholder="$t('station.state')">
            <el-option
              v-for="dict in dict.type.common_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{$t('common.confirm')}}</el-button>
        <el-button @click="cancel">{{$t('common.cancel')}}</el-button>
      </div>
    </el-dialog>

    <!-- 选择设备地图 -->
    <el-dialog width="85%" center :title="$t('station.selectAddress')" :visible.sync="innerVisible" :close-on-click-modal="false" append-to-body>
      <div>
        <div style="display: flex;justify-content: space-between;align-items: center;margin-bottom: 10px;">
          <!-- <el-input id="tipInput" v-model="poiKeywords" placeholder="请输入搜索名称"> -->
          <div>{{$t("station.pickAddress")}}</div>
          <el-autocomplete class="inline-input" size="small" v-model="poiKeywords" :fetch-suggestions="querySearch"
            :placeholder="$t('station.searchKey')" @select="handleSelect"></el-autocomplete>
        </div>
        <!-- <el-button slot="append" icon="el-icon-search" @click="searchKeyword" style="width:60px"></el-button> -->
        <!-- </el-input> -->
        <div ref="mapContainer" style="height:600px"></div>
        <div slot="footer" class="dialog-footer" align="right" style="margin-top:15px">
          <el-button type="primary" @click="confirmSelectAdress(1)">{{$t('common.confirm')}}</el-button>
          <el-button @click="confirmSelectAdress(0)">{{$t('common.cancel')}}</el-button>
        </div>
    </div>
  </el-dialog>

  <select-device ref="selectDevice" :companyId="this.companyId" @ok="handleSelectDevice"></select-device>
  <select-user @ok="onSelect" ref="selectUser" ></select-user>
  </div>
</template>

<script>
import selectDevice from "./selectDevice";
import { listStation, getStation, delStation, addStation, updateStation ,getStationDevices ,addBindingDevices , remBindingDevice,defaultDisplayDevice} from "@/api/ems/station";
import {companyOptions} from '@/api/ztIot/company'
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import AMapLoader from "@amap/amap-jsapi-loader";
import loadAMap from '@/utils/loadMap'
import selectUser from "../../system/user/selectUser";
export default {
  name: "Station",
  dicts: ['common_status','online_status'],
  components: {Treeselect,selectDevice,selectUser},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      baseEl:true,
      appendEl:false,
      // 总条数
      total: 0,
      // 设备站点表格数据
      stationList: [],
      companyList:[],
      deptOptions:[], 
      deviceList:[],
      // 弹出层标题
      title: "",
      poiKeywords:'',
      // 是否显示弹出层
      open: false,
      innerVisible:false,
      // 查询参数
      companyId:null ,
      baseUrl:process.env.VUE_APP_BASE_API,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        state: null,
      },
      // 表单参数
      form: {},
      //添加绑定表单
      addBindForm:{
        id:null ,
        defaultDeviceId:null 
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: this.$t('common.cannotbeempty',{name:this.$t('station.deviceName')}), trigger: "blur" }
        ],
        companyId: [
          { required: true, message: this.$t('common.cannotbeempty',{name:this.$t('station.company')}), trigger: "blur" }
        ],
        deptId: [
          { required: true, message: this.$t('common.cannotbeempty',{name:this.$t('station.group')}), trigger: "blur" }
        ],
        // ancestors: [
        //   { required: true, message: "组级列表不能为空", trigger: "blur" }
        // ],
        state: [
          { required: true, message: this.$t('common.cannotbeempty',{name:this.$t('station.deviceState')}), trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getCompanyList()
    this.getTreeselect()
  },
  mounted(){
    this.initMap()
  },
  methods: {
    async initMap() {
      const AMap = await loadAMap()
      this.map = new AMap.Map(this.$refs.mapContainer, {
        resizeEnable: true,
        zoom: 16, //初始化地图级别
        showIndoorMap: false,
      })
      AMap.plugin(['AMap.Scale', 'AMap.ToolBar', 'AMap.ControlBar'], () => {
        const Scale = new AMap.Scale()
        const toolBar = new AMap.ToolBar({
          position: 'RB',
          offset: new AMap.Pixel(150, 220)
        })
        const controlBar = new AMap.ControlBar()
        this.map.addControl(controlBar)
        this.map.addControl(toolBar)
        this.map.addControl(Scale)
      })
    },
    /** 查询设备站点列表 */
    getList() {
      this.loading = true;
      listStation(this.queryParams).then(response => {
        this.stationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
     /** 查询部门下拉树结构 */
     getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    //获取企业列表
    getCompanyList(){
      companyOptions().then( res => this.companyList = res.data )
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        companyId: null,
        deptId: null,
        ancestors: null,
        sumEnergy: null,
        sumPower:null,
        surplusEnergy: null,
        unit: null,
        powerUnit: null,
        longitude: null,
        latitude: null,
        address: null,
        state: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        masterId:null,
        masterName:null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = this.$t('station.addDeviceSite');
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getStation(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = this.$t('station.editDeviceSite');
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateStation(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.successful'));
              this.open = false;
              this.getList();
            });
          } else {
            addStation(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.successful'));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    //设备管理
    deviceManager(row){
      this.baseEl = false;
      this.appendEl = true ;
      this.companyId = row.companyId;
      this.addBindForm = {id : row.id , defaultDeviceId : row.defaultDeviceId}
      this.handleGetStationDevices(row.id)
    },
    handleGetStationDevices(id){
      getStationDevices(id).then(
        res => this.deviceList = res.data
      )
    },
    //绑定设备
    handleSelectDevice(objArray){
      this.addBindForm.deviceIdList = objArray.map( o => o.id)
      let params = this.addBindForm;
      addBindingDevices(params).then( res => {
        this.handleGetStationDevices(params.id)
        this.$modal.msgSuccess(res.msg);
      })
    },
    //关闭设备管理DIV
    handleCloseEl(){
      this.baseEl = true ; 
      this.appendEl = false;
    },
    //确认复制配置
    openSelectDevice(){
      this.$refs.selectDevice.show();
    }
    ,
    onOpen(){
      this.$refs["selectUser"].show()
    },
    /** 导出按钮操作 */
    onSelect(obj) {
      console.log(obj)
      if(obj) {
        this.form.masterId = obj[0].userId
        this.form.masterName = obj[0].nickName
      }
    },
    //设置为默认显示设备
    handleDefaultDisplayDevice(row){
      let param = {id:this.addBindForm.id,deviceId:row.id}
      defaultDisplayDevice(param).then(res =>{
        this.$modal.msgSuccess(res.msg);
        this.handleGetStationDevices(param.id);
      })
    },
    //解除设备绑定电站
    handleRemBindingDevice(row){
      this.$modal.confirm(this.$t('station.unbindDevice',{name:row.name})).then(function() {
        return remBindingDevice(row);
      }).then((res) => {
        this.handleGetStationDevices(this.addBindForm.id);
        this.$modal.msgSuccess(res.msg);
      }).catch(() => {});
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm(this.$t('station.deviceDeleteConfirm',{name:row.name})).then(function() {
        return delStation(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(this.$t('common.successful'));
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ems/station/export', {
        ...this.queryParams
      }, `station_${new Date().getTime()}.xlsx`)
    },
    querySearch(queryString, cb) {
      this.autoComplete.search(queryString, (status, result) => {
        var tips = result.tips || [];
        tips = tips.map(it => {
          it.value = it.name
          return it
        })
        // 调用 callback 返回建议列表的数据
        cb(tips);
      })
    },
    handleSelect(item) {
      this.placeSearch.setCity(item.adcode);
      this.placeSearch.search(item.name);
    },
    confirmSelectAdress(type) {
      // 确定
      if (type === 1) {
        if (this.currentSelectAddress) {
          const result = this.currentSelectAddress
          const { formattedAddress, addressComponent } = result
          const { location, province, city, district } = addressComponent
          this.form.longitude = location.lng
          this.form.latitude = location.lat
          this.form.address = formattedAddress
        }
      }
      this.innerVisible = false
    },
    POISearchDialog() {
      let _this = this;
      this.innerVisible = true
      this.currentSelectAddress = null
      this.poiKeywords = ''
      this.$nextTick(async () => {
        const AMap = await AMapLoader.load({
          key: this.mapConfig.MAPKEY, // 申请好的Web端开发者Key，首次调用 load 时必填
          version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
          plugins: ["AMap.Scale", "AMap.ToolBar", "AMap.Geolocation"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        });

        this.map = new AMap.Map(this.$refs.mapContainer, {
          //设置地图容器id
          viewMode: "3D", //是否为3D地图模式
          zoom: 12, //初始化地图级别-
          // center: [116.405467, 39.907761], //初始化地图中心点位置
        });
        AMap.plugin(['AMap.Geocoder', 'AMap.PlaceSearch', 'AMap.AutoComplete', 'AMap.Geolocation'], () => {
          var geolocation = new AMap.Geolocation({
            // 是否使用高精度定位，默认：true
            enableHighAccuracy: true,
            // 设置定位超时时间，默认：无穷大
            timeout: 10000,
            // 定位按钮的停靠位置的偏移量
            offset: [10, 20],
            //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            zoomToAccuracy: true,
            //  定位按钮的排放位置,  RB表示右下
            position: 'RB'
          })

          function onComplete(res) {
            const pointer = [res.position.lng, res.position.lat]
            // data是具体的定位信息
            _this.map.setCenter(pointer);
          }

          function onError(res) {
            // 定位出错
            console.error(res.message)
          }
          geolocation.getCurrentPosition(function (status, result) {
            if (status == 'complete') {
              onComplete(result)
            } else {
              onError(result)
            }
          });
          var autoOptions = {
            //city 限定城市，默认全国
            city: '广州',
            input: "tipinput"
          };
          // 实例化AutoComplete
          const geocoder = new AMap.Geocoder()
          this.autoComplete = new AMap.AutoComplete(autoOptions);
          this.placeSearch = new AMap.PlaceSearch({
            pageSize: 10, // 单页显示结果条数
            pageIndex: 1, // 页码
            map: this.map, // 展现结果的地图实例
            autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
          });
          this.placeSearch.on('markerClick', (e) => {
            const { location } = e.data
            geocoder.getAddress(location, (status, result) => {
              if (status === 'complete' && result.regeocode) {
                const { addressComponent } = result.regeocode
                addressComponent.location = location
                this.currentSelectAddress = result.regeocode
              }
            })
          })
          // 监听鼠标点击地图点，生成marker
          this.map.on('click', (ev) => {
            if (this.currentMarker) {
              this.map.remove(this.currentMarker);
            }
            const { lng, lat } = ev.lnglat
            var marker = new AMap.Marker({
              icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
              position: [lng, lat],
              offset: new AMap.Pixel(-10, -27),
            });
            this.currentMarker = marker
            this.map.add(marker);
            geocoder.getAddress(ev.lnglat, (status, result) => {
              if (status === 'complete' && result.regeocode) {
                const { addressComponent } = result.regeocode
                addressComponent.location = ev.lnglat
                this.currentSelectAddress = result.regeocode
              }
            })
          });
        })
      })

    },
  }
};
</script>
